<?php
/**
 * @author zouhao
 *	qq:16852868
 *	zouhao619@gmail.com
 */
abstract class CommonController extends Controller {
	public $tpl = null;
	public $table = CONTROLLER_NAME;
	public $useModel = false;
	public $order = 'id desc';
	public $group=null;
	public $where=null;
	public function init() {
		if (empty ( $_SESSION ['admin'] )) {
			$this->redirect ( 'Public/login' );
		}
		if (! in_array ( $this->table . '/' . METHOD_NAME, $_SESSION ['accessList'] )) {
			$this->error ( '权限不够!' );
		}
		$this->assign ( 'title', array_search ( $this->table . '/' . METHOD_NAME, $_SESSION ['accessList'] ) );
	}
	public function index() {
		if ($this->useModel) {
			$db = D ( $this->table );
		} else {
			$db = M ( $this->table );
		}
		$count = $db->where($this->where)->group($this->group)->count (); // 计算总数
		$p = new Page ( $count );
		$list = $db->order ( $this->order )->where($this->where)->group($this->group)->limit ( $p->firstRow . ',' . $p->listRows )->select ();
		$page = $p->show ();
		$this->assign ( "page", $page );
		$this->assign ( "list", $list );
		$this->display ( $this->tpl );
	}
	public function save() {
		if ($this->isGet ()) {
			$this->display ( $this->tpl );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			if ($db->save ( $_POST )) {
				$this->redirect ( 'index' );
			} else {
				$this->error ($db->getError()?$db->getError():'添加失败');
			}
		}
	}
	public function update() {
		if ($this->isGet ()) {
			if ($this->useModel) {
				$info = D ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
			} else {
				$info = M ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
			}
			$this->assign ( 'info', $info );
			if ($this->tpl == null)
				$this->display ( 'save' );
			else
				$this->display ( $this->tpl );
		} else {
			$db = D ( $this->table );
			$db->create () or $this->error ( $db->getError () );
			if ($db->update ( $_POST )) {
				$this->redirect ( 'index' );
			} else {
				$this->error ($db->getError()?$db->getError():'编辑失败' );
			}
		}
	}
	public function read() {
		if ($this->useModel) {
			$info = D ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
		} else {
			$info = M ( $this->table )->where ( 'id=' . intval ( $_GET ['id'] ) )->find ();
		}
		$this->assign ( 'info', $info );	
		$this->display ( $this->tpl );
	}
	public function delete() {
		if ($this->useModel) {
			$db = D ( $this->table );
		} else {
			$db = M ( $this->table );
		}
		if (isset ( $_GET ['id'] )) {
			$rs = $db->delete ( array (
					'id' => $_GET ['id'] 
			) );
		} else {
			$rs = $db->delete ( array (
					'id' => array (
							'in',
							$_POST ['id'] 
					) 
			) );
		}
		if ($rs) {
			$this->redirect ( 'index' );
		} else {
			$this->error ( '删除失败,请联系员工' );
		}
	}
}
